<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Illuminate\Support\Facades\Log;

class BackupDatabase extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    //protected $signature = 'command:name';
    protected $signature = 'db:backup';
    /**
     * The console command description.
     *
     * @var string
     */
    //protected $description = 'Command description';
    protected $description = 'Backup the databse';

    protected $process;
    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
        $name = config('database.connections.mysql.database'). date('Y-m-d_H:i:s') . ".sql";
        $this->process = new Process(sprintf(
            '/usr/local/mysql/bin/mysqldump -h%s -u%s -p%s %s >%s',
            config('database.connections.mysql.host'),
            config('database.connections.mysql.username'),
            config('database.connections.mysql.password'),
            config('database.connections.mysql.database'),
            storage_path('app/public/backup/'. $name)
        ));
    }

/**
* Execute the console command.
*
* @return mixed
*/
    public function handle()
    {
        //
        //Log::error("database auto save");
        try {
            $this->process->mustRun();
            $this->info('The backup has been proceed successfully.');
        } catch (ProcessFailedException $exception){
            Log::error($exception->getMessage());
            Log::error("The backup process has been failed.");
            $this->error('The backup process has been failed.');
        }
    }
}
